package com.controller;

import com.po.Alltype;
import com.po.Coach;
import com.po.Course;
import com.service.CommentService;
import com.service.CourseService;
import com.util.DataFormat;
import com.util.UploadUtil;
import com.vo.CourseQuery;
import com.vo.CourseVo;
import com.vo.TrainerCourseQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 阳幸子 on 2018/5/8.
 */
@Controller
public class CourseController {
    @Autowired
    private CourseService courseService;


    @Autowired
    private CommentService commentService;

    @Value("${img.location}")
    public  String location;
    @RequestMapping("/course_manager")
    public String course_manager(int page,Model model){
        List<Alltype> listType=courseService.selectAlltype();
        List<Coach> listCoach=courseService.selectAllCoach();
        int count=courseService.count();
        int pageSize=0;
        if(count%6==0){
            pageSize=count/6;
        }else{
            pageSize=count/6+1;
        }
        if(page>0){
            page=(page-1)*6;
        }
        List<Course> courses=courseService.selectCourseByPage(page);
        List<com.vo.Course> listCourse=new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            Course course =  courses.get(i);
            com.vo.Course vcourse=new com.vo.Course();
            cloneCourse(course,vcourse);
            Alltype type=courseService.selectTypeById(course.getCourse_type_id());

            Coach coach=courseService.selectCoachById(course.getCoach_id());
            vcourse.setCoach(coach);
            vcourse.setCourseType(type);
            listCourse.add(vcourse);
        }
        model.addAttribute("countCourse",count);
        model.addAttribute("listCourse",listCourse);
        model.addAttribute("pageSize",pageSize);

        return "/manager/course_manager";
    }

    public static void cloneCourse(Course course,com.vo.Course vcourse){
        vcourse.setCtype(course.getCtype());
        vcourse.setCourseDesc(course.getCourse_desc());
        vcourse.setEndTime(course.getEnd_time());
        vcourse.setStartTime(course.getStart_time());
        vcourse.setId(course.getId());
        vcourse.setLikeCount(course.getLike_count());
        vcourse.setCourseName(course.getCourse_name());
        vcourse.setPhoto(course.getPhoto());
    }
    @RequestMapping(value = "/add_course")
    public String add_course(Model model){
        List<Alltype> listType=courseService.selectAlltype();
        List<Coach> listCoach=courseService.selectAllCoach();

        model.addAttribute("listType",listType);
        model.addAttribute("listCoach",listCoach);
        return "/manager/add_course";
    }


    @RequestMapping(value = "/add_courseForm",method = RequestMethod.POST)
    public String addCourseForm(CourseVo courseVo, @RequestParam("file") MultipartFile file,HttpSession session){

        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        System.out.println("webappRoot-----" +classpath);
        String webappRoot = classpath.replaceAll("target/classes/", "") + "src/main/resources/static/upload/";
        System.out.println("webappRoot-----" + webappRoot);

        // 获取图片的文件名
        String fileName = file.getOriginalFilename();
        // 获取图片的扩展名
        String extensionName = StringUtils.substringAfter(fileName, ".");
        // 新的图片文件名 = 获取时间戳+"."图片扩展名
        String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;

        boolean res = false;
        try {
            res = UploadUtil.uploadFile(file.getBytes(),webappRoot,newFileName);


        } catch (IOException e) {
            e.printStackTrace();
        }

        Course course= DataFormat.voFormat(courseVo);
        if(res){
            course.setPhoto(newFileName);
        }
        courseService.insertCourse(course);
        System.out.println(course);
        return "redirect:/course_manager?page=1";
    }

    @RequestMapping(value = "/edit_course")
    public String edit_course(Model model,long id){
        List<Alltype> listType=courseService.selectAlltype();
        List<Coach> listCoach=courseService.selectAllCoach();
        Course course=courseService.selectCourseById(id);
        model.addAttribute("course",course);
        model.addAttribute("listType",listType);
        model.addAttribute("listCoach",listCoach);
        return "/manager/edit_course";
    }

    @RequestMapping(value = "/edit_courseForm",method = RequestMethod.POST)
    public String edit_courseForm(CourseVo courseVo, @RequestParam("file") MultipartFile file,@RequestParam("id") long id,HttpSession session){
        Course course= DataFormat.voFormat(courseVo);
        course.setId(id);
        if(file!=null){


            // 获取图片的文件名
            String fileName = file.getOriginalFilename();
            // 获取图片的扩展名
            String extensionName = StringUtils.substringAfter(fileName, ".");
            // 新的图片文件名 = 获取时间戳+"."图片扩展名
            String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
            String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
            System.out.println("classpath-----" +classpath);
            String webappRoot = classpath.replaceAll("target/classes/", "") + "src/main/resources/static/upload/";
            System.out.println("webappRoot-----" + webappRoot);

            boolean res = false;
            try {
                res = UploadUtil.uploadFile(file.getBytes(),webappRoot,newFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(res){
                courseVo.setPhoto(newFileName);
            }
        }

        courseService.updateCourse(course);
        System.out.println(course);
        return "redirect:/course_manager?page=1";
    }

    @RequestMapping("/del_course")
    public String delCourse(long id){
        courseService.delCourse(id);
        return  "redirect:/course_manager?page=1";
    }
    @RequestMapping("/selectCourse")
    public String selectCourse(long id, Model model, HttpSession session){

        List<Alltype> listType=courseService.selectAlltype();
        List<Coach> listCoach=courseService.selectAllCoach();
        Course course=courseService.selectCourseById(id);
        com.vo.Course vcourse=new com.vo.Course();
        cloneCourse(course,vcourse);
        Alltype type=courseService.selectTypeById(course.getCourse_type_id());

        Coach coach=courseService.selectCoachById(course.getCoach_id());
        vcourse.setCoach(coach);
        vcourse.setCourseType(type);
        model.addAttribute("course",vcourse);

        return "/manager/course_detail";
    }

    @RequestMapping("/trainer_courseById")
    public String selectByTrainerCourse(@RequestParam("id") long id,@RequestParam("page") int page,Model model){
        int count=courseService.count();
        int pageSize=0;
        if(count%6==0){
            pageSize=count/6;
        }else{
            pageSize=count/6+1;
        }
        if(page>0){
            page=(page-1)*6;
        }
        TrainerCourseQuery trainerCourseQuery=new TrainerCourseQuery();
        trainerCourseQuery.setPage(page);
        trainerCourseQuery.setId(id);
        List<Course> courses=courseService.selectCourseByTrainer(trainerCourseQuery);

        List<com.vo.Course> listCourse=new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            Course course =  courses.get(i);
            com.vo.Course vcourse=new com.vo.Course();
            cloneCourse(course,vcourse);
            Alltype type=courseService.selectTypeById(course.getCourse_type_id());

            Coach coach=courseService.selectCoachById(course.getCoach_id());
            vcourse.setCoach(coach);
            vcourse.setCourseType(type);
            listCourse.add(vcourse);
            System.out.println(vcourse);
        }


        List<Alltype> listType=courseService.selectAlltype();
        model.addAttribute("listCoachCourse",listCourse);
        model.addAttribute("listType",listType);
        model.addAttribute("pageSize",pageSize);
        return "/trainer/trainer_course";
    }

    @RequestMapping("/trainer_eventById")
    public String selectByTrainerEvent(@RequestParam("id") long id,@RequestParam("page") int page,Model model){
        int count=courseService.countEvent();
        int pageSize=0;
        if(count%6==0){
            pageSize=count/6;
        }else{
            pageSize=count/6+1;
        }
        if(page>0){
            page=(page-1)*6;
        }
        TrainerCourseQuery trainerCourseQuery=new TrainerCourseQuery();
        trainerCourseQuery.setPage(page);
        trainerCourseQuery.setId(id);
        List<Course> courses=courseService.selectEventByTrainer(trainerCourseQuery);
        List<com.vo.Course> listCourse=new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            Course course =  courses.get(i);
            com.vo.Course vcourse=new com.vo.Course();
            cloneCourse(course,vcourse);
            Alltype type=courseService.selectTypeById(course.getCourse_type_id());

            Coach coach=courseService.selectCoachById(course.getCoach_id());
            vcourse.setCoach(coach);
            vcourse.setCourseType(type);
            listCourse.add(vcourse);
            System.out.println(vcourse);
        }
        List<Alltype> listType=courseService.selectAlltype();
        trainerCourseQuery.setId(id);
        trainerCourseQuery.setPage(page);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("listCoachEvent",listCourse);
        model.addAttribute("listType",listType);
        return "/trainer/trainer_events";
    }
    @RequestMapping("/selectAllQueryCourse")
    public String selectAllQueryCourse(int page, String scourse_type_id, String ptype,Model model,HttpSession session){
        int current=0;
        long course_type_id=0;
        if(scourse_type_id!=null){
            course_type_id=Long.parseLong(scourse_type_id);
        }

        CourseQuery courseQuery=new CourseQuery();
        int totalcount=courseService.count()+courseService.countEvent();
        int pageSize=0;
        if(totalcount%3==0){
            pageSize=totalcount/3;
        }else{
            pageSize=totalcount/3+1;
        }
        if(page>0){
           current=(page-1)*3;
        }
        courseQuery.setPage(current);
        courseQuery.setPageSize(3);
        if(course_type_id!=0){
            courseQuery.setCourse_type_id(course_type_id);
        }else{
            courseQuery.setCourse_type_id(0);
        }
        if(ptype!=null&&ptype.equals("")==false){
            courseQuery.setPtype(null);
        }
        System.out.println("courseQuery...."+courseQuery);
        List<Course> listAllCourse=courseService.selectAll(courseQuery);
        List<Alltype> listType=courseService.selectAlltype();
        List<com.vo.Course> listCourse=new ArrayList<>();
        for (int i = 0; i < listAllCourse.size(); i++) {
            Course course=listAllCourse.get(i);
            com.vo.Course vcourse=new com.vo.Course();
            cloneCourse(course,vcourse);
            int commentCount=commentService.countById(course.getId());
            vcourse.setCommentCount(commentCount);
            listCourse.add(vcourse);
            System.out.println(vcourse);
        }
        courseQuery.setPage(page);
        model.addAttribute("courseQuery",courseQuery);
        session.setAttribute("courseQuery",courseQuery);
        model.addAttribute("pageSize",pageSize);
        model.addAttribute("listAllCourse",listCourse);
        model.addAttribute("listType",listType);
        return "/blog";
    }
    @RequestMapping("/selectCourseDetail")
    public String selectCourseDetail(long id,Model model){

        List<Alltype> listType=courseService.selectAlltype();
        Course course=courseService.selectCourseById(id);
        List<com.vo.Comment> listComment=commentService.selectByCourseId(id);
        model.addAttribute("course",course);
        model.addAttribute("listType",listType);
        model.addAttribute("listComment",listComment);

        return "/single";
    }

}
